<?php

require_once __DIR__.DS.'blgEntity.php';

class BlgUser extends BlgEntity {
	
	function __construct($data, $type='guid'){
		$this->load($data, $type);
	}
	
	/**
	 * Loader for this object
	 * @param mixed $data
	 * @param string $type
	 * @throws Exception
	 */
	protected function load($data, $type='guid'){
		$this->initializeAttributes();
		
		switch($type){
			case 'guid':
				$query=	blg_dbschema_query_buid(blg_dbschema_select_users(array(
					'guid' => $data,
					'type' => 'user'
				)));
				$result= blg_dbschema_select($query);
				break;
			case 'email':
				$query=	blg_dbschema_query_buid(blg_dbschema_select_users(array(
					'email' => $data,
					'type' => 'user'
				)));
				$result= blg_dbschema_select($query);		
				break;
			case 'username':
				$query=	blg_dbschema_query_buid(blg_dbschema_select_users(array(
					'username' => $data,
					'type' => 'user'
				)));
				$result= blg_dbschema_select($query);						
				break;
			case 'code':
				$query=	blg_dbschema_query_buid(blg_dbschema_select_users(array(
					'code' => $data,
					'type' => 'user'
				)));
				$result= blg_dbschema_select($query);						
				break;				
			default:
				throw new Exception($type." is not a valid user type loader!");				
		}
		
		if($result->num_rows==1){			
			$this->attributes= $result->{0};
		}else{
			throw new Exception("$data ($type) is not valid data for loading of a user!");
		}			
	}
	
	/**
	 * (non-PHPdoc)
	 * @see engine/clases/BlgEntity::initializeAttributes()
	 */
	protected function initializeAttributes(){
		parent::initializeAttributes();
	}
	
	/**
	 * Reload object from DB
	 */
	protected function reload(){
		if(!empty($this->attributes['guid'])){
			$this->load($this->attributes['guid'], 'guid');
			return TRUE;
		}			
		return FALSE;
	}
	
	/**
	 * Save changes made to user's attributes
	 */
	public function save(){
		$attributes= $this->attributes;
		
		//blg_entity
		unset($attributes['type']);
		unset($attributes['subtype']);
		unset($attributes['owner_guid']);
		unset($attributes['site_guid']);
		unset($attributes['container_guid']);
		unset($attributes['access_id']);
		unset($attributes['time_created']);
		unset($attributes['time_updated']);
		unset($attributes['last_action']);
		unset($attributes['enabled']);
		//blg_users_entity
		unset($attributes['salt']);
		unset($attributes['banned']);
		unset($attributes['admin']);
		unset($attributes['prev_last_action']);
		unset($attributes['last_login']);
		unset($attributes['prev_last_login']);		
		
		/*
		'guid' => string '53' (length=2)      
		'name' => string 'Marta' (length=5)
		'surname' => string '' (length=0)
		'username' => string 'marta' (length=5)
		'password' => string 'c914d106a524ba383dea6870a336c414' (length=32)
		'email' => string 'martolas@yopmail.com' (length=20)
		'language' => string 'es' (length=2)
		'code' => string 'Tf638V5ovKQsXghAksRRMNEL7vngg9hO' (length=32)
		*/   

		$query= blg_dbschema_query_buid(blg_dbschema_update_users(
			array('guid' => $attributes['guid']),
			$attributes
		));
		$result= blg_dbschema_update($query);
		
		if($result->success && $result->affected_rows>0){
			parent::save();
			return TRUE;
		}
		
		return FALSE;
	}
	
	/**
	 * Update user password
	 */
	public function change_password($new_password){
		$this->attributes['password']= md5(SALT.$new_password.$this->attributes['salt']);
		$query= blg_dbschema_query_buid(blg_dbschema_update_users(
			array('guid' => $this->attributes['guid']),
			array('password' => $this->attributes['password'])			
		));
		$result= blg_dbschema_update($query);		
		return $result->success;
	}
	
	/**
	 * Login this user
	 */
	public function login(){		
		$guid_logged_in= blg_get_logged_in_user_guid();
		if(!empty($guid_logged_in))
			blg_logout();
		
		blg_login($this->attributes['guid']);
		return TRUE;
	}
	
	/**
	 * Logout this user
	 */
	public function logout(){
		$guid_logged_in= blg_get_logged_in_user_guid();

		if($guid_logged_in==$this->attributes['guid']){
			blg_logout();
			return TRUE;
		}
		
		return FALSE;
	}
	
	/**
	 * Ban this user
	 */
	public function ban(){
		if(blg_ban_user($this->attributes['guid'])){
			$this->attributes['banned']= 'yes';
			return TRUE;
		}
		return FALSE;
	}
	
	/**
	 * Unban this user
	 */
	public function unban(){
		if(blg_unban_user($this->attributes['guid'])){
			$this->attributes['banned']= 'no';
			return TRUE;
		}
		return FALSE;
	}
	
	public function is_banned(){
		return ($this->attributes['banned']=='yes');		
	}
	
	public function is_not_active(){
		return ($this->attributes['banned']=='validation');		
	}	

	/**
	 * Make user Administrator
	 */
	public function make_admin(){
		if(blg_user_make_admin($this->attributes['guid'])){
			$this->attributes['admin']= 'yes';
			return TRUE;
		}
		return FALSE;
	}
	
	/**
	 * Remove user as Administrator
	 */
	public function revoke_admin(){
		if(blg_user_revoke_admin($this->attributes['guid'])){
			$this->attributes['admin']= 'no';
			return TRUE;
		}
		return FALSE;
	}

	/**
	 * Send validation email to user if not validated yet
	 */
	public function send_validation_email(){
		if($this->attributes['banned']=='validation'){
			blg_user_send_validation_email($this->attributes['guid']);
			return TRUE;
		}		
		return FALSE;
	}
	

	
	/**
	 * Save last user action time 
	 */
	public function save_last_action($time= NULL){
		if(blg_user_last_action($this->attributes['guid'], $time)){
			$this->reload();
			return TRUE;
		}		
		
		return FALSE;
	}
	
	/**
	 * Save last user login time
	 */
	public function save_last_login($time=NULL){
		if(blg_user_last_login($this->attributes['guid'], $time)){
			$this->reload();
			return TRUE;
		}
		return FALSE;
	}
	
	/**
	 * Returns the user URL
	 */
	public function getURL(){
		return blg_get_site_url().'user/'.$this->attributes['username'].'/';
	}
	
	/**
	 * Returns the validation URL for this user
	 */
	public function getValidationURL(){
		return blg_get_site_url().'action/user/validate?e='.urlencode($this->attributes['email']).'&c='.blg_user_get_validation_code($this).'&'.blg_security_url();
	}

	/**
	 * Returns the URL to reset user's password
	 */
	public function getResetPasswordURL(){
		return blg_get_site_url().'action/user/password/reset?e='.urlencode($this->attributes['email']).'&c='.blg_user_get_validation_code($this).'&'.blg_security_url();
	}	
	
	/**
	 * Get user image
	 */
	public function getIcon($size='medium'){
		//TODO
	}
	
	/* STATIC */
	
	public static function create($name, $username, $email, $password1, $password2){
		if(FALSE!==($user_guid= blg_new_user($name, $username, $email, $password1, $password2)))
			return new BlgUser($user_guid);
			
		return FALSE;
	}
}

